'use client'

import React, { useEffect, useRef } from 'react'
import twemoji from 'twemoji'

interface EmojiProps {
  emoji: string
  className?: string
  size?: string | number
}

const Emoji: React.FC<EmojiProps> = ({ emoji, className = '', size = '1em' }) => {
  const emojiRef = useRef<HTMLSpanElement>(null)

  useEffect(() => {
    if (emojiRef.current) {
      try {
        const parsedEmoji = twemoji.parse(emoji, {
          folder: 'svg',
          ext: '.svg',
          base: 'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/',
          size: 'svg'
        })
        emojiRef.current.innerHTML = parsedEmoji
        
        // Set image styles
        const img = emojiRef.current.querySelector('img')
        if (img) {
          img.style.width = typeof size === 'number' ? `${size}px` : size
          img.style.height = typeof size === 'number' ? `${size}px` : size
          img.style.display = 'inline-block'
          img.style.verticalAlign = 'middle'
          img.style.objectFit = 'contain'
          
                  // Add error handling
        img.onerror = () => {
          // If CDN fails, fallback to native emoji
            if (emojiRef.current) {
              emojiRef.current.innerHTML = emoji
            }
          }
        }
      } catch (error) {
        // If twemoji parsing fails, display native emoji directly
        console.warn('Twemoji parse failed, falling back to native emoji:', error)
        if (emojiRef.current) {
          emojiRef.current.innerHTML = emoji
        }
      }
    }
  }, [emoji, size])

  return (
    <span 
      ref={emojiRef} 
      className={`inline-block emoji-twemoji ${className}`}
      style={{ fontSize: typeof size === 'number' ? `${size}px` : size }}
    >
      {emoji}
    </span>
  )
}

export default Emoji 